<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/6
 * Time: 14:22
 */
namespace Api\Domain;

use Admin\Api\AddressApi;
use Admin\Api\SecurityCodeApi;
use Api\Model\ErrorCodeModel;
use Common\Api\AccountApi;
use Common\Api\BoyeServiceApi;
use Common\ConstVar\BoyeActionConstModel;
use Shop\Api\MemberConfigApi;
use Shop\Api\RedEnvelopeApi;
use Tool\Api\AreaApi;
use Tool\Api\CityApi;
use Tool\Api\ProvinceApi;
use Uclient\Api\UserApi;
use Uclient\Model\OAuth2TypeModel;
use Uclient\Model\UcenterMemberModel;
use Admin\Model\SecurityCodeModel;

use Ucenter\Api\MemberApi;

class UserDomain extends BaseDomain
{

    protected $business_code = 'user';

    protected $allowType = array("json", "rss", "html");

    /**
     * 更新身份证号，实名认证
     */
    public function updateIDNumber(){

        $this->checkVersion(100);

        addLog("User/updateIDNumber", $_GET, $_POST, $this->client_id . "调用实名认证接口!");

        $uid = $this->_post('uid', 0,"用户ID无效!");
        $name = $this->_post('name', '','真实姓名参数缺失!');
        $idnumber = $this->_post('idnumber', '',"身份证号参数缺失!");

        $result = apiCall(MemberConfigApi::SAVE_BY_ID,array($uid,array('identity_validate'=>1)));

        if(!$result['status']){
            $this->apiReturnErr($result['info'],$this->business_code.'01');
        }

        $entity = array(
            'realname'=>$name,
            'idnumber'=>$idnumber,
        );

        $result = apiCall(MemberApi::SAVE_BY_ID,array($uid,$entity));

        if(!$result['status']){
            $this->apiReturnErr($result['info'],$this->business_code.'02');
        }else{
            $this->apiReturnSuc($result['info']);
        }
    }

    public function loginByCode(){

        $this -> checkVersion(100);

        if(IS_POST){
            addLog("User/loginByCode",$_GET,$_POST,$this->client_id."调用用户手机验证码登录接口");

            $mobile = $this -> _post('mobile','','手机号参数缺失');
            $code = $this -> _post('code','','验证码参数缺失');

            $type = SecurityCodeModel::TYPE_FOR_LOGIN;

            $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$mobile,$type));

            if($result['status']) {
                $result = apiCall(UserApi::FIND,array(array('mobile'=>$mobile)));

                if(!$result['status']){
                    $this -> apiReturnErr($result['info']);
                }

                if(is_null($result['info'])){
                    $this -> apiReturnErr("该手机未注册！");
                }

                $uid = $result['info']['id'];

                $result = apiCall(AccountApi::GET_INFO, array($uid));

                action_log(BoyeActionConstModel::API_USER_LOGIN, "member", $uid, $uid);

                $this->apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }
    }

    /**
     * 微信用户更换手机号
     */
    public function weixinChangePhone(){
        $this->checkVersion(100);
        if(IS_POST) {
            addLog("User/changePhone", $_GET, $_POST, $this->client_id . "调用用户手机更换接口!");
            $ori_mobile = $this->_post('ori_mobile','','原手机号无效');
            $uid = $this->_post('uid', 0,"用户ID无效!");
            $code = $this->_post('code', '',"密码无效");
            $mobile = $this->_post('mobile', '',"新手机无效");//新手机

            if($ori_mobile == $mobile){
                $this -> apiReturnErr('手机号码未更改');
            }


            $type = SecurityCodeModel::TYPE_FOR_CHANGE_NEW_PHONE;
            //1. 验证－验证码
            $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE, array($code, $mobile, $type));

            if (!$result['status'] || empty($result['info'])) {
                $this->apiReturnErr("验证码错误!",'10');
            }

            //2. 验证新手机是否已经被其它账户绑定过
            $result = apiCall(UserApi::FIND,array(array('mobile'=>$mobile)));
            if($result['status'] && is_array($result['info'])){
                $this->apiReturnErr("无法绑定该手机号，因为已经绑定其它账号!",'11');
            }

            //3. 验证-密码是否有限
            $result = apiCall(UserApi::FIND,array(array('id'=>$uid)));

            if (!$result['status']) {
                $this->apiReturnErr($result['info'],'12');
            }
            if($ori_mobile != $result['info']['mobile']){
                $this->apiReturnErr("原手机号有误!".$ori_mobile,'13');
            }

            $this->updateMobile($uid,$mobile);

            $this->apiReturnSuc("更换成功!");

        }

    }

    /**
     * 更换手机号
     */
    public function changePhone(){
        $this->checkVersion(100);

        if(IS_POST) {
            addLog("User/changePhone", $_GET, $_POST, $this->client_id . "调用用户手机更换接口!");
            $password = $this->_post('password','','密码参数缺失');
            $uid = $this->_post('uid', 0,"用户ID无效!");
            $code = $this->_post('code', '',"密码无效");
            $mobile = $this->_post('mobile', '',"新手机无效");//新手机


            $type = SecurityCodeModel::TYPE_FOR_CHANGE_NEW_PHONE;
            //1. 验证－验证码
            $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE, array($code, $mobile, $type));

            if (!$result['status'] || empty($result['info'])) {
                $this->apiReturnErr("验证码错误!",'10');
            }

            //2. 验证新手机是否已经被其它账户绑定过
            $result = apiCall(UserApi::FIND,array(array('mobile'=>$mobile)));
            if($result['status'] && is_array($result['info'])){
                $this->apiReturnErr("无法绑定该手机号，因为已经绑定其它账号!",'11');
            }

            //3. 验证-密码是否有限
            $result = apiCall(UserApi::FIND,array(array('id'=>$uid)));
            $mdPsw = itboye_ucenter_md5($password,UC_AUTH_KEY);

            if (!$result['status']) {
                $this->apiReturnErr($result['info'],'12');
            }
            if($mdPsw != $result['info']['password']){
                $this->apiReturnErr("密码错误!".$mdPsw,'13');
            }

            $this->updateMobile($uid,$mobile);

            $this->apiReturnSuc("更换成功!");

        }

    }

    /**
     * 新手机绑定
     */
    public function bind(){
        $this->checkVersion(100);

        if(IS_POST){
            addLog("User/bind",$_GET,$_POST,$this->client_id."调用用户手机绑定接口!");
            $username = $this->_post('mobile','',"手机不能为空");//传入一般为手机号
            $uid = $this->_post('uid',0,"uid为空");
            $code = $this->_post('code','',"验证码错误");
            $password = $this -> _post('password','','密码不能为空');

            if(strlen($password) < 6 || strlen($password) > 64){
                $this -> apiReturnErr('密码的长度必须大于6小于64');
            }
            if(!preg_match("/^[0-9a-zA-Z\\\\,.?><;:!@#$%^&*()_+-=\[\]\{\}\|]{6,64}$/",$password)){
                $this -> apiReturnErr('密码只能包含数字、英文字母以及如下字符 \,.?><;:!@#$%^&*()_+-=!');
            }

            $type = SecurityCodeModel::TYPE_FOR_NEW_BIND_PHONE;

            $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$username,$type));

            if (!$result['status'] || empty($result['info'])) {
                $this->apiReturnErr("验证码错误!");
            }

            //验证通过，表明手机可用

            $result = apiCall(UserApi::FIND,array(array('mobile'=>$username)));
            if($result['status'] && is_array($result['info'])){
                $this->apiReturnErr("该手机号已绑定另外一个账号!");
            }

            $password = think_ucenter_md5($password, UC_AUTH_KEY);
            $entity = array(
                'password' => $password,
            );
            $result = apiCall(UserApi::SAVE_BY_ID,array($uid,$entity));
            if(!$result['status']){
                $this -> apiReturnErr($result['info']);
            }

            $this->updateMobile($uid,$username);

        }

        $this->apiReturnErr("非法请求!");

    }

    /**
     * 更新密码
     */
    public function updatePsw(){

        addLog("User/updatePsw",$_GET,$_POST,'应用'.$this->client_id."调用更新密码接口");
        $this->checkVersion(100);
        //
        if(IS_POST){

            $username = $this->_post('username','','用户名缺失');
            $old_psw = $this->_post('old_psw','','旧密码缺失');
            $psw = $this->_post('psw','','新密码缺失');

            //$code = $this->_post('code','',"验证码参数缺失");

            /*if(empty($old_psw) && empty($code)){
                $this->apiReturnErr("验证参数缺失!");
            }*/

            //验证码存在时，排除密码
            /*if(!empty($code)){
                $old_psw = '';
            }*/

            //$old_psw = base64_decode($old_psw);

            //$psw = base64_decode($psw);
            $type = $this->getUsernameType($username);

            $result = array('status');
            if($type == UcenterMemberModel::ACCOUNT_TYPE_MOBILE){
                $result = apiCall(UserApi::FIND,array(array('mobile'=>$username)));
            }elseif($type == UcenterMemberModel::ACCOUNT_TYPE_USERNAME){
                $result = apiCall(UserApi::FIND,array(array('username'=>$username)));
            }else{
                $this->apiReturnErr("参数非法!");
            }



            if (!$result['status'] && empty($result['info'])) {
                $this->apiReturnErr("用户登录账户非法!");
            }

            $id = $result['info']['id'];

           // addLog("id",$id,$psw,"");
            //**************检测是否合法用户，要修改密码，必须确保用户身份有权限******

           /* if(!empty($code)){

                $type = SecurityCodeModel::TYPE_FOR_UPDATE_PSW; //

                $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$username,$type));
                if(!$result['status']){
                    $this->apiReturnErr("验证失败");
                }

            }elseif(!empty($old_psw)) {
                if ($result['info']['password'] != think_ucenter_md5($old_psw, UC_AUTH_KEY)) {
                    $this->apiReturnErr("原密码错误!");
                }
            }*/


            if(!empty($old_psw)) {
                if ($result['info']['password'] != think_ucenter_md5($old_psw, UC_AUTH_KEY)) {
                    $this->apiReturnErr("原密码错误!");
                }
            }


            //**************************************************************
            if(strlen($psw) < 6){
                $this->apiReturnErr("密码必须大于6位长度!");
            }
            addLog("User/updatePsw",$_GET,$_POST,'应用'.$this->client_id."调用更新密码接口");
            $result = apiCall(UserApi::UPDATEPWD,array($id,$psw));
            //记录成功更新密码的日志
            action_log(BoyeActionConstModel::API_USER_UPADTE_PSW, "member", $id,$this->client_id);

            if (!$result['status']) {
                $this->apiReturnErr("更新密码失败!".$result['info']);
            }

            $this->apiReturnSuc("更新密码成功!");

        }else{
            $this->apiReturnErr("更新密码失败!");
        }
    }

    /**
     * POST: 登录
     * @internal param post.username
     * @internal param post.password
     */
    public function login()
    {
        $username = $this->_post("username","","用户名缺失");

        $password = $this->_post("password","","密码缺失");

        $type = $this->getUsernameType($username);

        $notes = "应用" . $this->client_id . ":[用户" . $username . "],调用登录接口,密码：" . $password.'用户类型:'.$type;

        addLog("User/login", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        $result = apiCall(AccountApi::LOGIN, array($username, $password, $type));

        if ($result['status']) {

            $uid = $result['info'];

            $result = apiCall(AccountApi::GET_INFO, array($uid));

            if(!$result['status']){
                $this->apiReturnErr($result['info']);
            }

            action_log(BoyeActionConstModel::API_USER_LOGIN, "member", $uid, $uid);

            $this->apiReturnSuc($result['info']);

        } else {
            $this->apiReturnErr($result['info']);
        }

    }

    /**
     * POST: 注册
     * username 用户名
     * password 密码
     * mobile 手机
     * realname真实姓名
     * email 电子邮箱
     * idnumber身份证号
     * birthday生日
     */
    public function register()
    {

        $notes = "应用" . $this->client_id . "，调用注册接口";

        addLog("User/register", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        if (IS_POST) {

            $type = $this->_post("reg_type", 1);
            $username = $this->_post("username", "","用户名缺失");
            $code = $this->_post("code","","验证码缺失");
            $from = $this->_post("from", 0);
            $error = $this->isLegal($type,$username,$from);
            $password = $this->_post("password","","密码缺失");

            //可选参数
            $email = $this->_post("email", '');
            $invite_id = $this->_post("invite_id", 0);
            $sex = $this->_post("sex", 0);

            $map = array(
                'idcode' => $invite_id,
            );
            $result = apiCall(MemberConfigApi::GET_INFO,array($map));
            if($result['status']){
                $invite_id = $result['info']['uid'];
            }else{
                $this -> apiReturnErr($result['info']);
            }

            if (!($error === false)) {
                $this->apiReturnErr($error,ErrorCodeModel::Invalid_Parameter);
            }



            $mobile = "";
            $idcode = "";

            if($type == UcenterMemberModel::ACCOUNT_TYPE_MOBILE){

                if($code){

                }

                $mobile = $username;

                //验证码验证
                $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$mobile,SecurityCodeModel::TYPE_FOR_REGISTER));
                if(!$result['status']){
                    $this->apiReturnErr($result['info']);
                }

                $username = 'M'.$mobile;

                $idcode = getIDCode($mobile,'M');
            }


            $nickname = $this->_post("nickname", "初来乍到");

            $entity = array(
                'username' => $username,
                'password' => $password,
                'from' => $from,
                'mobile' => $mobile,
                'realname' => '',
                'nickname' => $nickname ,
                'email' => $email,
                'idnumber' => '',
                'birthday' => time(),
                'idcode'=>$idcode,
                'type'=>$type,
                'invite_id'=>$invite_id,
                'sex'=>$sex,
            );

            $result = apiCall(AccountApi::REGISTER, array($entity));

            if ($result['status']) {

                $uid = $result['info'];

                $result = apiCall(RedEnvelopeApi::REG_ADD,array($uid));

                $flag = 0;

                if(!$result['status']){
                    $flag = 1;
                }

                $result = apiCall(MemberApi::RAISE_SCORE,array($uid,50));

                if(!$result['status']){
                    $flag = 1;
                }

                if($invite_id != "" && is_numeric($invite_id)){
                    $result = apiCall(MemberApi::RAISE_SCORE,array($invite_id,100));
                }

                if($flag == 1){
                    $this -> apiReturnSuc($uid."注册成功!红包或者积分发放出现错误,请联系管理员!");
                }else{
                    $this ->apiReturnSuc($uid);
                }


            } else {
                $this->apiReturnErr($result['info']);
            }
        } else {
            $this->apiReturnErr("只支持POST请求!");
        }

    }

    /**
     * 用户信息更新
     */
    public function update()
    {
        $notes = "应用" . $this->client_id . "，调用用户更新接口";

        addLog("User/update", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        if (IS_POST) {
            $uid = $this->_post('uid', 0,'intval');

            if($uid <= 0){
                $this->apiReturnErr("用户ID非法!");
            }

            $mobile = $this->_post("mobile", "");
            $realname = $this->_post("realname", "");
            $email = $this->_post("email", "");
            $idnumber = $this->_post("idnumber", "");
            $birthday = strtotime($this->_post("birthday", 0));
            $nickname = $this->_post("nickname", "");
            $sex = $this->_post("sex", "");
            $qq = $this->_post("qq", "");
            $head = $this->_post("head", "");

            $entity = array();

            if($sex!=""){
                $entity['sex'] = $sex;
            }
            if(!empty($head)){
                $entity['head'] = $head;
            }

            if(!empty($qq)){
                $entity['qq'] = $qq;
            }
            if(!empty($birthday)){
                $entity['birthday'] = $birthday;
            }
            if(!empty($idnumber)){
                $entity['idnumber'] = $idnumber;
            }
            if(!empty($email)){
                $entity['email'] = $email;
            }
            if(!empty($realname)){
                $entity['realname'] = $realname;
            }
            if(!empty($nickname)){
                $entity['nickname'] = $nickname;
            }

            if(!empty($mobile)){
                $entity['mobile'] = $mobile;
            }

            $result = apiCall(AccountApi::UPDATE, array($uid, $entity));

            if ($result['status']) {
                $this->apiReturnSuc("操作成功！");
            } else {
                $this->apiReturnErr($result['info']);
            }
        }
    }

    /**
     *找回密码
     */
    public function findPswByMobile()
    {
        $notes = "应用" . $this->client_id . "，调用手机找回密码接口";

        addLog("User/findPswByMobile", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        if (IS_POST) {

            $mobile = $this->_post('mobile', 0);
            $code = $this->_post('code', '');
            $psw = $this->_post('psw', '');

            $type=SecurityCodeModel::TYPE_FOR_UPDATE_PSW;

            $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$mobile,$type));

            if ($result['status']==false) {
                $this->apiReturnErr("验证码错误");
            }

                $result = apiCall(UserApi::FIND, array(array('mobile' => $mobile)));
                $id = $result['info']['id'];

                addLog("id", $id, $psw, "");

                $result = apiCall(UserApi::UPDATEPWD, array($id, $psw));
                //记录成功更新密码的日志
                action_log(BoyeActionConstModel::API_USER_UPADTE_PSW, "member", $id, $this->client_id);

                if (!$result['status']) {
                    $this->apiReturnErr("更新密码失败!" . $result['info']);
                }

                $this->apiReturnSuc("更新密码成功!");

            } else {
                $this->apiReturnErr("更新密码失败!");
            }
        }

    /**
     * 用户地址添加
     */
    public function addressAdd(){

        $notes = "应用" . $this->client_id . "，调用用户地址添加接口";

        addLog("User/addressAdd", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        if(IS_POST){

            $mobile = $this->_post('mobile','','用户手机缺失');
            $provinceid = $this->_post('provinceid','','省缺失');
            $cityid = $this->_post('cityid','','市缺失');
            $areaid = $this->_post('areaid','','区缺失');

            //可选参数
            $contactname = $this->_post('contactname',' ');

            //查询该手机号注册的帐号ID
            $result = apiCall(UserApi::FIND, array(array('mobile' => $mobile)));
            if($result['status']){
                if(empty($result['info'])){
                    $this->apiReturnErr('该手机号未注册');
                }else{
                    $uid = $result['info']['id'];
                }
            }else{
                $this->apiReturnErr($result['info']);
            }

            //根据省城市代码查询 省
            $result = apiCall(ProvinceApi::GET_INFO,array(array('provinceID' => $provinceid)));
            if(!empty($result['info'])){
                $province = $result['info']['province'];
            }else{
                $province = ' ';
            }


            //根据省城市代码查询 市
            $result = apiCall(CityApi::GET_INFO,array(array('cityID' => $cityid)));
            if(!empty($result['info'])){
                $city = $result['info']['city'];
            }else{
                $city = ' ';
            }
            //根据省城市代码查询 市
            $result = apiCall(AreaApi::GET_INFO,array(array('areaID' => $areaid)));
            if(!empty($result['info'])){
                $area = $result['info']['area'];
            }else{
                $area = ' ';
            }

            //身份证
            $result = apiCall(MemberApi::GET_INFO,array(array('uid' => $uid)));
            if(!empty($result['info'])){
                $idnumber = $result['info']['idnumber'];
            }else{
                $idnumber = ' ';
            }

            //保存地址信息
            $entity = array(
                'uid'=>$uid,
                'country'=>'中国',
                'city'=>$city,
                'province'=>$province,
                'detailinfo'=>$province.$city.$area,
                'area'=>$area,
                'wxno'=>' ',
                'areaid'=>$areaid,
                'postal_code'=>0,
                'id_card'=>$idnumber,
                'cityid'=>$cityid,
                'provinceid'=>$provinceid,
                'contactname'=>$contactname,
                'mobile'=>$mobile
            );

            //$this->apiReturnErr($entity);
            $result = apiCall(AddressApi::ADD,array($entity));

            if ($result['status']) {
                $this->apiReturnSuc('添加成功');
            } else {
                $this->apiReturnErr($result['info']);
            }

        }else{
            $this->apiReturnErr("只支持POST请求!");
        }

    }

    /**
     * 用户地址查询
     */
    public function addressQuery(){

        $notes = "应用" . $this->client_id . "，调用用户地址查询接口";

        addLog("User/addressQuery", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        if(IS_POST){
            $uid = $this->_post('uid',0,'用户ID缺失');

            $map['uid'] = $uid;
            $order = 'id asc';
            $result = apiCall(AddressApi::QUERY_NO_PAGING,array($map,$order));

            if(!$result['status']){
                $this->apiReturnErr($result['info']);
            }else{
                $this->apiReturnSuc($result['info']);
            }

        }else{
            $this->apiReturnErr("只支持POST请求!");
        }

    }

    /**
     * 用户地址删除
     */
    public function addressDelete(){

        $notes = "应用" . $this->client_id . "，调用用户地址删除接口";

        addLog("User/addressDelete", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        if(IS_POST){

            $id = $this->_post('id',0,'id缺失');

            $map['id'] = $id;
            $result = apiCall(AddressApi::DELETE,array($map));

            if(!$result['status']){
                $this->apiReturnErr($result['info']);
            }else{
                $this->apiReturnSuc('删除成功');
            }

        }else{
            $this->apiReturnErr("只支持POST请求!");
        }

    }

    /**
     * 检查这些参数是否合法
     * @param $type
     * @param $username
     * @param $from
     * @return bool|string
     */
    private function isLegal($type,$username,$from){

        //TODO: 检查from的值是否合法
        //TODO: 检测用户账号是否合法
        //1. $type = 1 的时候 $username 是用户名
        //2. $type = 2 的时候 $username 是邮箱,应该符合邮箱规则
        //3. $type = 4 的时候 $username 是手机,应该符合手机的规则
        $from = intval($from);

        if(!OAuth2TypeModel::checkType($from)){
            return "用户来源参数无效";
        }

        if($type == UcenterMemberModel::ACCOUNT_TYPE_MOBILE && $this->getUsernameType($username) != $type){
            //$this->apiReturnErr($type." ".$this->getUsernameType($username))    ;
            $this->apiReturnErr("手机号非法!");
        }

        $notes=  "检测用户名:".$username."来源";

        $result =  apiCall(UserApi::CHECK_USER_NAME,array($username));
        if(!$result['status']){
            return "用户名已被注册!";
        }

        $result = apiCall(UserApi::CHECK_MOBILE,array($username));
        if(!$result['status']){
            return "手机号已被注册";
        }


        addLog("isLegal",$result,"",$notes);

        return false;

    }

    /**
     * 更新用户手机号
     * @param $uid
     * @param $mobile
     */
    private function updateMobile($uid,$mobile){

        $entity = array(
            'phone_validate'=>1,
        );

        $result = apiCall(UserApi::SAVE_BY_ID,array($uid,array('mobile'=>$mobile)));
        if($result['status']){
            $result = apiCall(MemberConfigApi::SAVE_BY_ID,array($uid,$entity));
            if($result['status']){
                $this->apiReturnSuc("绑定成功!");
            }else{
                $this->apiReturnErr($result['info']);
            }
        }else{
            $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 检测登录账户的类型
     * 3: 手机号
     * 2:  EMAIL
     * @param $str
     * @return int
     */
    private function getUsernameType($str){

        //return $str." ".preg_match("/^1\d{10}$/",$str);

        if(preg_match("/^1\d{10}$/",$str)){
            return UcenterMemberModel::ACCOUNT_TYPE_MOBILE;
        }

        return UcenterMemberModel::ACCOUNT_TYPE_USERNAME;
    }

}